﻿#if (DEBUG && TRACE)
#define DEBUG_TRACE
#endif

using System.Diagnostics;

namespace TestEffectiveCS
{
    /// <summary>
    /// 使用Conditional特性代替#if条件编译
    /// </summary>
    public class Test04
    {
        public class Person
        {
            string _lastName = string.Empty;
            public string LastName 
            {
                get
                {
                    CheckState();
                    return _lastName;
                }
                set
                {
                    //CheckState();
                    _lastName = value;
                    CheckState();
                }
            }

            string _firstName = string.Empty;


            //多个环境变量之间的组合关系是“或（OR）”
            //DEBUG或TRACE如果需要“与（AND）”还是得用预处理符号
            //[Conditional("DEBUG"),
            //Conditional("TRACE")]
            [Conditional("DEBUG_TRACE")]
            //Conditional不能在方法内使用，也不能用于有返回值的函数上
            private void CheckState()
            {
                //获取正在被调用函数的名称：
                string methodName = new StackTrace().GetFrame(1).GetMethod().Name;
                Trace.WriteLine("Entering CheckState for Person:");
                Trace.Write("\tcalled by");
                Trace.WriteLine(methodName);

                Debug.Assert(_lastName != null, 
                    methodName, 
                    "Last name cannot be null");

                Debug.Assert(_lastName.Length > 0,
                    methodName,
                    "Last name cannot be blank");

                Debug.Assert(_firstName != null,
                    methodName,
                    "First name cannot be null");

                Debug.Assert(_firstName.Length > 0,
                    methodName,
                    "First name cannot be blank");

                Trace.WriteLine("Exiting CheckState for Person");
            }
        }

        public Test04()
        {
            Test04.Person p = new Test04.Person();
            p.LastName = "";
            string lastName = p.LastName;
        }
    }
}